package com.passer.toolbox.tfile.command;

import com.passer.toolbox.common.core.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class FileCreate {

    private String sameNameFolderParent;

    public void createSameNameFolder(String filePath) {
        File file = new File(StringUtils.isEmpty(filePath) ? "." : filePath);
        if (file.isFile()) {
            createFolder(file);
        } else {
            createSameNameFolderByFolder(file);
        }
    }

    public void createSameNameFolderByFolder(File folder) {
        if (!folder.exists()) {
            System.out.println(folder.getAbsolutePath() + " 不存在！");
            return;
        }
        File[] files = folder.listFiles();
        if (files == null || files.length == 0) {
            System.out.println(folder.getAbsolutePath() + "中无文件！");
            return;
        }
        for (File file : files) {
            if (file.isFile()) {
                createFolder(file);
            } else {
                createSameNameFolderByFolder(file);
            }
        }
    }

    private void createFolder(File file) {
        if (!file.exists()) {
            System.out.println(file.getAbsolutePath() + " 不存在！");
            return;
        }
        File parent;
        if (StringUtils.isEmpty(this.sameNameFolderParent)) {
            parent = file.getParentFile();
        } else {
            parent = new File(file.getParentFile(), this.sameNameFolderParent);
        }
        String fileName = file.getName();
        File newFolder = new File(parent, fileName.substring(0, fileName.lastIndexOf('.')));
        if (newFolder.exists()) {
            System.out.println(newFolder.getAbsolutePath() + "已存在！");
            return;
        }
        if (!newFolder.mkdirs()) {
            System.out.println(newFolder.getName() + "文件夹创建失败！");
        } else {
            System.out.println(newFolder.getName() + "文件夹创建成功！");
        }
    }
}
